﻿using System;
using System.Text;
using System.Windows;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
//using System.Windows.Forms;
using System.Diagnostics;
using System.Configuration;
using LocumUpdate;
using System.Threading;
using System.Windows.Threading;
using Update;
using System.Windows.Input;
using System.Collections;
using System.Xml;

namespace DosyaUpload
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        FtpDownload ftpd;
        public Window1()
        {
            checkWorkingCopies();
            InitializeComponent();

            if (StaticClass.TYPE_STARTUP == STARTUP_TYPES.EXPLICIT)
            {
                showWindow();
            }
            else
            {
                updateButton.Visibility = Visibility.Collapsed;
            }
            if (!(StaticClass.TYPE_STARTUP == STARTUP_TYPES.EXPLICIT))
            {
                updateButton_Click(null, null);
            }
        }
        private void checkWorkingCopies()
        {
            bool hasError = false;
            Process a = Process.GetCurrentProcess();
            Process[] li = Process.GetProcessesByName(a.ProcessName);

            if (li.Length > 1)
            {
                // Çalışan kopyalar zaten var demektir.
                if (!(StaticClass.TYPE_STARTUP == STARTUP_TYPES.EXPLICIT))
                {
                    Environment.Exit(0);
                }
                frmMessageBox xxx = new frmMessageBox("Diğer çalışan programlar kapatılsın mı ?");
                xxx.Topmost = true;
                xxx.ShowDialog();

                if (xxx.DialogResult == true)
                {
                    try
                    {
                        foreach (Process p in li)
                        {
                            if (p.Id != a.Id)
                            {
                                p.Kill();
                                p.WaitForExit();
                            }
                        }
                    }
                    catch (Exception)
                    {
                        hasError = true;
                    }
                }
                else
                {
                    foreach (Process p in li)
                    {
                        if (p.Id != a.Id)
                        {
                            activateProcess(p);
                        }
                    }

                    Environment.Exit(0);
                }
                if (hasError)
                {
                    Environment.Exit(0);
                }
            }
        }

        string filePath = string.Empty;

        private bool checkForNewVersion()
        {
            if (Baglanti.IsInternetBaglantisi() == false)
            {
                return false;
            }
            string[] strFileList = null;
            filePath = Path.GetTempPath() + "test\\";
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            strFileList = ftpd.getStreamGetList("ftp://aymed-urodynami.com/htdocs/AymedProjects/" + StaticClass.ConfigName);
            if (strFileList == null)
                return false;
            if (!File.Exists(Environment.CurrentDirectory + "\\" + StaticClass.ConfigName))
            {
                strFileList = null;
                return false;
            }

            if (strFileList.Length > 0)
            {
                ftpd.getStreamDownload(filePath, StaticClass.ConfigName, "ftp://aymed-urodynami.com/htdocs/AymedProjects/" + StaticClass.ConfigName);

                int majorFtp = 0, minorFtp = 0, revisionFtp = 0;
                int majorLocal = 0, minorLocal = 0, revisionLocal = 0;

                string textstr = string.Empty;
                textstr = ftpd.getVersion(filePath + StaticClass.ConfigName);

                if (textstr != "")
                {
                    string[] xSplit = textstr.Split('.', '/', ' ');
                    majorFtp = Convert.ToInt32(xSplit[1]);
                    minorFtp = Convert.ToInt32(xSplit[2]);
                    revisionFtp = Convert.ToInt32(xSplit[3]);
                }

                textstr = ftpd.getVersion(Environment.CurrentDirectory + "\\" + StaticClass.ConfigName);
                int k = 1;
                if (textstr != "")
                {
                    string[] xSplit = textstr.Split('.', '/', ' ');

                    if (xSplit[0] == "Beta" || xSplit[0] == "beta")
                        k++;
                    majorLocal = Convert.ToInt32(xSplit[k]);
                    minorLocal = Convert.ToInt32(xSplit[k + 1]);
                    revisionLocal = Convert.ToInt32(xSplit[k + 2]);
                }

                if (k > 1 || (majorFtp > majorLocal) || (majorFtp == majorLocal && minorFtp > minorLocal)
                          || (majorFtp == majorLocal && minorFtp == minorLocal && revisionFtp > revisionLocal))
                {


                }
                else
                {
                    return false;
                }
            }
            else { return false; }


            return true;
        }

        private bool downloadZip()
        {
            string[] fileDetay;
            String[] strFileList =
                ftpd.getStreamGetList("ftp://aymed-urodynami.com/htdocs/AymedProjects/" + StaticClass.updateFile);

            if (strFileList != null)
            {
                fileDetay = strFileList[0].Split(' ');
                int fileLength = Convert.ToInt32(fileDetay[fileDetay.Length - 5]);
                Dispatcher.Invoke(DispatcherPriority.DataBind, (ThreadStart)delegate()
                {
                    progressBar1.Maximum = fileLength;
                });

                try
                {
                    ftpd.ftpDownloadUpdate += new FtpDownloadUpdate(ftpd_ftpDownloadUpdate);
                    bool dlStreamRes = ftpd.getStreamDownload(filePath, StaticClass.updateFile, "ftp://aymed-urodynami.com/htdocs/AymedProjects/" + StaticClass.updateFile);
                    if (dlStreamRes)
                        return true;
                }
                catch (Exception)
                {
                    strFileList = null;
                    return false;
                }
            }
            else
            {
                return false;
            }
            return false;

        }

        void ftpd_ftpDownloadUpdate(int downloaded, int totalDownload)
        {

            Dispatcher.Invoke(DispatcherPriority.DataBind, (ThreadStart)delegate()
            {
                progressBar1.Value = downloaded;
            });
        }

        private void showWindow()
        {
            Width = 300;
            Height = 240;
            WindowStyle = WindowStyle.SingleBorderWindow;
        }

        private bool copyZippedFiles()
        {

            if (ftpd.zipFile(filePath + StaticClass.updateFile, filePath) == true)
            {
                File.Delete(filePath + StaticClass.updateFile);
                String[] strFileList = Directory.GetFiles(filePath);
                foreach (string itemDosyaAdi in strFileList)
                {
                    try
                    {
                        string destFileName = Environment.CurrentDirectory + "\\" + Path.GetFileName(itemDosyaAdi);
                        File.Copy(itemDosyaAdi, destFileName, true);
                        File.Delete(itemDosyaAdi);
                    }
                    catch (Exception)
                    {

                    }
                }
                Directory.Delete(filePath, true);
            }
            return true;
        }

        private bool startDownload()
        {
            ftpd = new FtpDownload("aymedftp1989", "rlpItcz0ae", "ftp://aymed-urodynami.com/htdocs/AymedProjects/");

            bool hasNewRevision = checkForNewVersion();

            if (hasNewRevision)
            {
                bool userResult = false;
                this.Dispatcher.Invoke(DispatcherPriority.DataBind, (ThreadStart)delegate()
                {

                    MessageBoxResult msgResult = MessageBox.Show(this, "Programın yeni sürümü bulundu. Güncelleme yapmak istermisiniz...?", "AYMED"
                      , MessageBoxButton.YesNo);
                    if (msgResult == MessageBoxResult.Yes)
                    {
                        showWindow();
                        userResult = true;
                    }
                });

                if (userResult)
                {
                    bool dlResult = downloadZip();
                    if (dlResult)
                    {

                        this.Dispatcher.Invoke(DispatcherPriority.DataBind, (ThreadStart)delegate()
                        {
                            progressBar1.Value = progressBar1.Maximum;
                        });
                        if (StaticClass.processID > 0)
                        {
                            try
                            {
                                Process p = Process.GetProcessById(StaticClass.processID);
                                p.Kill();
                                p.WaitForExit();
                            }
                            catch (Exception) { }
                        }
                        copyZippedFiles();
                        showMessage("Güncelleme Başarıyla Tamamlandı");
                        try
                        {

                            if (!(StaticClass.TYPE_STARTUP == STARTUP_TYPES.EXPLICIT))
                            {
                                Process.Start(Environment.CurrentDirectory + "\\" +
                                    StaticClass.ConfigName.Replace(".Config", ""));
                            }
                        }
                        catch (Exception) { }
                        //}
                    }
                    else
                    {
                        showMessage("Güncelleme Sırasında Hata Oluştu");
                    }
                }
            }
            else
            {
                if (StaticClass.TYPE_STARTUP == STARTUP_TYPES.EXPLICIT ||
                    StaticClass.TYPE_STARTUP == STARTUP_TYPES.BY_USER_ON_PROGRAM)
                {
                    showMessage("Sürümünüz Günceldir.");
                }
                return false;
            }
            return true;
        }

        private void showMessage(String message)
        {
            this.Dispatcher.Invoke(DispatcherPriority.DataBind, (ThreadStart)delegate()
            {
                MessageBox.Show(this, message, "AYMED");
            });

        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (File.Exists(filePath))
                Directory.Delete(filePath, true);
        }

        private void updateButton_Click(object sender, RoutedEventArgs e)
        {

            if (checkBox1.Visibility == Visibility.Visible &&
                StaticClass.TYPE_STARTUP == STARTUP_TYPES.EXPLICIT)
            {
                if ((bool)checkBox1.IsChecked)
                {
                    StaticClass.programType = StaticClass.PROGRAM_DYS;
                }
                else
                {
                    StaticClass.programType = StaticClass.PROGRAM_SUITE;
                }
               // StaticClass.initializeGlobalVariables();

            }
           

            updateButton.IsEnabled = false;
            label1.Visibility = Visibility.Visible;
            Thread t = new Thread((ThreadStart)delegate()
            {
                button1_Click(null, null);

                bool startDownloadRes = startDownload();
                this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate()
                {
                    if (!(StaticClass.TYPE_STARTUP == STARTUP_TYPES.EXPLICIT))
                    {
                        Close();
                    }
                    updateButton.IsEnabled = true;
                    label1.Visibility = Visibility.Collapsed;
                }));

            });
            t.IsBackground = true;
            t.Start();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (!(StaticClass.TYPE_STARTUP == STARTUP_TYPES.EXPLICIT))
            {
                this.Width = 0;
                this.Height = 0;
            }
        }

        private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (Keyboard.IsKeyDown(Key.LeftCtrl) &&
                Keyboard.IsKeyDown(Key.LeftAlt) &&
                Keyboard.IsKeyDown(Key.F12))
            {

                checkBox1.Visibility = Visibility.Visible;
            }
        }

        #region Window activate code
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
        static extern bool ShowWindow(IntPtr hWnd, ShowWindowEnum flags);
        private enum ShowWindowEnum
        {
            Hide = 0,
            ShowNormal = 1, ShowMinimized = 2, ShowMaximized = 3,
            Maximize = 3, ShowNormalNoActivate = 4, Show = 5,
            Minimize = 6, ShowMinNoActivate = 7, ShowNoActivate = 8,
            Restore = 9, ShowDefault = 10, ForceMinimized = 11
        };

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern int SetActiveWindow(int hwnd);

        [DllImport("user32.dll")]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
        const UInt32 WM_SYSCOMMAND = 0x0112;
        const UInt32 SC_RESTORE = 0xF120;



        private void activateProcess(Process bProcess)
        {
            if (bProcess.MainWindowHandle != IntPtr.Zero)
                SendMessage(bProcess.MainWindowHandle, (uint)WM_SYSCOMMAND, (IntPtr)SC_RESTORE, (IntPtr)0);

            return;

            //System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName("notepad");
            //if (p.Length > 0)
            //{
            //  SetForegroundWindow(p[0].MainWindowHandle);
            //}

            //SetForegroundWindow(bProcess.MainWindowHandle);
            //return;


            //get the (int) hWnd of the process
            int hwnd = (int)bProcess.MainWindowHandle;
            //MessageBox.Show("" + hwnd);
            //check if its nothing
            if (hwnd != 0)
            {
                //if the handle is other than 0, then set the active window
                SetActiveWindow(hwnd);
            }
            else
            {
                //we can assume that it is fully hidden or minimized, so lets show it!
                ShowWindow(bProcess.Handle, ShowWindowEnum.Restore);
                SetActiveWindow((int)bProcess.MainWindowHandle);

            }
        }

        #endregion

        XmlProcess xmlp = null;
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            #region Update.xml
            string path = Path.GetTempPath();

            ftpd = new FtpDownload("aymedftp1989", "rlpItcz0ae", "ftp://aymed-urodynami.com/htdocs/AymedProjects/");
            bool durum = ftpd.getStreamDownload(path, "Update.xml", "ftp://aymed-urodynami.com/htdocs/AymedProjects/Update.xml");

            //path = @"H:\KYSY SOURCE CODE\25.01.2012_Kys\Kys\bin\Debug\Update.xml";          
            Thread.Sleep(10);
            if (!durum && !File.Exists(path + "Update.xml"))
                return;
            XmlDocument xml = new XmlDocument();
            xml.Load(path + "Update.xml");
           
            XmlElement root = xml.DocumentElement;
            xmlp = new XmlProcess();
            XmlNodeList xnList = xml.SelectNodes(root.Name);
      
            foreach (XmlNode node in xnList)
            {
             //   MessageBox.Show(StaticClass.programType.ToString());
                xmlp.ProcessChildHeaders(node, node, "ProductId", StaticClass.programType.ToString ());
            }
            if (xmlp.hasXml !=null && xmlp.hasXml.Count > 0)
            {
                StaticClass.updateFile = xmlp.hasXml["FolderName"].ToString();
                StaticClass.ConfigName = xmlp.hasXml["ConfigName"].ToString();
                //xmlp.hasXml["UpdateFile"];
            //    System.Windows.Forms.MessageBox.Show(StaticClass.programType.ToString());
            }
          
           
            File.Delete(path + "Update.xml");

            #endregion
        }
    }
}
